package com.tscnd.core.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class HttpRequestUtil {
	/**
	 * 
	 * <p>Title: doHttpPost</p>
	 * <p>Desc: </p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2016年3月31日 上午11:52:48 
	 * @version 1.0
	 * @param dataType(application/json,text/xml)
	 * @param data
	 * @param URL
	 * @return
	 */
	public static String doHttpPost(String dataType ,String data, String URL) {
		
		System.out.println("发起的数据:" + data);
		byte[] dataArray = data.getBytes();
		InputStream instr = null;
		try {
			URL url = new URL(URL);
			URLConnection http = url.openConnection();
			http.setDoOutput(true);
			http.setDoInput(true);
			http.setUseCaches(false);
			http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			http.setRequestProperty("Content-Type", dataType+";charset=utf-8");
			http.setRequestProperty("Content-length",String.valueOf(dataArray.length));
			System.out.println(String.valueOf("字符长度："+dataArray.length));
			DataOutputStream printout = new DataOutputStream(http.getOutputStream());
			printout.write(dataArray);
			printout.flush();
			printout.close();
			instr = http.getInputStream();

			//byte[] bis = IOUtils. .toByteArray(instr);
			 ByteArrayOutputStream output = new ByteArrayOutputStream();
			 byte[] buffer = new byte[1024*4];
		     int n;
		     while ((n = instr.read(buffer)) != -1) {
		        output.write(buffer, 0, n);
		     }
		    byte[] bis=output.toByteArray();
			String ResponseString = new String(bis, "UTF-8");
			if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
				System.out.println("返回空");
			}
			System.out.println("返回数据为:" + ResponseString);
			return ResponseString;
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		} finally {
			try {
				instr.close();
			} catch (Exception ex) {
				return "0";
			}
		}
	}
	
	
	/**
	 * 
	 * <p>Title: httpClinetPost</p>
	 * <p>Desc: </p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2016年4月1日 下午4:25:25 
	 * @version 1.0
	 * @param urlHead  请求地址
	 * @param urlPath  到方法级别的地址路径
	 * @param params   请求参数
	 * @return
	 * @throws HttpException
	 * @throws Exception
	 */
	public static String httpClinetPost(String urlHead, String urlPath, Map<String, String> params) throws HttpException,Exception{
		final HttpClient httpClient = new HttpClient();
		final PostMethod method = new PostMethod(urlHead + urlPath);
		method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
		if (params != null) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				if(entry.getKey()!=null&&entry.getValue()!=null){
					method.setParameter(entry.getKey(), entry.getValue());
				}
			}
		}
		
		String response = "";
		try {
			httpClient.executeMethod(method);
			response=method.getResponseBodyAsString();	
		} catch (HttpException e) {
			throw new HttpException("\n request HttpException:"+e.getMessage());
		} catch (IOException e) {
			throw new IOException("\n request HttpException:"+e.getMessage());
		} finally {
			method.releaseConnection();
		}
		return response;
	}
	
	public static String httpClinetGet(String urlHead, String urlPath, Map<String, String> params) throws HttpException,Exception{
		final HttpClient httpClient = new HttpClient();
 		
		StringBuffer strbuff=new StringBuffer();
 	   if (params != null) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				if(entry.getKey()!=null&&entry.getValue()!=null){
					String value=java.net.URLEncoder.encode(entry.getValue(), "utf-8");
		 			String b=  entry.getKey()+"="+value+"&";
		 			strbuff.append(b);
				}
			}
		}
 	   	String data=strbuff.toString();
 	    if(data.endsWith("&")){
      		data = data.replaceAll(".$", "");
  	    }
		final GetMethod method = new GetMethod(urlHead + urlPath+"?" + data);
		method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
		
		String response = "";
		try {
			httpClient.executeMethod(method);
			response = method.getResponseBodyAsString();
		} catch (HttpException e) {
			throw new HttpException("\n request HttpException:"+e.getMessage());
		} catch (IOException e) {
			throw new IOException("\n request HttpException:"+e.getMessage());
		} finally {
			method.releaseConnection();
		}
		return response;
	}
	
	/**
	 * 解析http请求的response
	 * 
	 * @param method
	 * @return 请求结果
	 * @throws IOException
	 */
//	public static String parserResponse(Object method) throws IOException {
//		PostMethod postMethod=null;
//		GetMethod getMethod=null;
//		InputStream in=null;
//		BufferedReader reader=null;
//		if(method instanceof PostMethod){
//			 postMethod=(PostMethod)method;
//			 in = postMethod.getResponseBodyAsStream();
//			 reader = new BufferedReader(new InputStreamReader(in, postMethod.getResponseCharSet()));
//		}else if(method instanceof GetMethod){
//			 getMethod=(GetMethod)method;
//			 in = getMethod.getResponseBodyAsStream();
//			 reader = new BufferedReader(new InputStreamReader(in, getMethod.getResponseCharSet()));
//		}
//		StringBuffer contentBuffer = new StringBuffer();
//		String inputLine = null;
//		if(reader!=null){
//			while ((inputLine = reader.readLine()) != null) {
//				contentBuffer.append(inputLine);
//				contentBuffer.append("/n");
//			}
//		}
//		// 去掉结尾的换行符
//		contentBuffer.delete(contentBuffer.length() - 2, contentBuffer.length());
//		if(in!=null){
//			in.close();
//		}
//		return contentBuffer.toString();
//	}
	
	/**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String doHttpGet(String url, Map<String,String>param) {
        String result = "";
        BufferedReader in = null;
        try {
        	List<Map.Entry<String, String>> mapEntrys = new ArrayList<Map.Entry<String, String>>(param.entrySet());  
     		StringBuffer strbuff=new StringBuffer();
     	    for (Entry<String, String> entry : mapEntrys) {
     	    	String value=java.net.URLEncoder.encode(entry.getValue(), "utf-8");
     			String b=  entry.getKey()+"="+value+"&";
     			strbuff.append(b);
     		}
     	    String data=strbuff.toString();
     	    if(data.endsWith("&")){
	       		data = data.replaceAll(".$", "");
       	    }
            String urlNameString = url + "?" + data;
            System.out.println("请求信息:"+urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            @SuppressWarnings("unused")
			Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
    public static void main(String[] args){
    	String str="123&123&";
    	
    	if(str.endsWith("&")){
    		String b = str.replaceAll(".$", "");
        	System.out.println("QQQ:"+b);
    	}else{
    		System.out.println("MM:"+str);
    	}
    }
}
